if (localStorage.getItem("id") && localStorage.getItem("token")) {
    $.ajax({
        url: "http://localhost:8888/users/info",
        method: "get",
        data: {
            id: localStorage.getItem("id")
        },
        headers: {
            authorization: localStorage.getItem("token")
        },
        success: function (res) {
            console.log(res);
            yonghu(res.info.nickname)
            tuichu()
        }
    })

} else {
    console.log("没有");
}
function yonghu(a) {
    $(".header-left").html(`
    <span>您好! ${a} </span>
    <a href="login.html">退出</a>

    `)
}
function tuichu() {
    $(".header-left>a").on("click", function () {
        if(confirm("是否确定退出")){
            $.ajax({
                url: "http://localhost:8888/users/logout",
                method: "get",
                headers: {
                    authorization:localStorage.getItem("token")
                },
                data: {
                    id: localStorage.getItem("id")
                },
                success: function (res) {
                    console.log(res);
                    alert(res.message)
                    location.href = "home.html"
                    localStorage.removeItem("id")
                    localStorage.removeItem("token")
                }
            })
        }
        return false
    })
}
$(".geren>p:nth-of-type(4)").on("click", function () {
    if (localStorage.getItem("id") && localStorage.getItem("token")) {
        location.href = `account.html`
    } else {
        alert("请先登录")
    }
    return false
})
var a = $("body>section>.box>table>tbody")
// 获取购物车
if (localStorage.getItem("id")) {
    $.ajax({
        url: "http://localhost:8888/cart/list",
        data: {
            id: localStorage.getItem("id"),
        },
        headers: {
            authorization: localStorage.getItem("token")
        },
        success: function (res) {
            console.log(res);
            const num = res.cart.length
            tBody(num, res)
        }
    })
} else {
    location.href = "login.html"
}

// 加载页面
function tBody(num, res) {
    var str = ``
    for (let i = 0; i < num; i++) {
        str += `
        <tr >
            <td class="theadOne" >
                <input type="checkbox" name="checkbox" index="${i}" goodsId=${res.cart[i].goods_id}>
                <img src="${res.cart[i].img_small_logo}" alt="">
                <p>${res.cart[i].title}</p>
            </td>
            <td>
                <span>${res.cart[i].current_price}</span>
            </td>
            <td>
                <button goodsId=${res.cart[i].goods_id}>-</button>
                <input type="text" value="${res.cart[i].cart_number}" goodsId=${res.cart[i].goods_id}>
                <button goodsId=${res.cart[i].goods_id}>+</button>
            </td>
            <td>
                <em onoff="true">${(res.cart[i].cart_number) * (res.cart[i].current_price)} </em>
            </td>
            <td>
                <b index="${res.cart[i].goods_id}">删除</b>
            </td>
        </tr>
        <div></div>
        `

    }
    $("body>section .box table tbody")[0].innerHTML = str
    // 计算总价
    function Total() {
        var total = 0;
        for (let i = 0; i < $("body>section .box table tbody em").length; i++) {
            if ($("body>section .box table tbody em")[i].getAttribute("onoff") === "true") {
                total += +$("body>section .box table tbody em")[i].innerText
            }

        }
        total = total.toFixed(2)
        $("body>section .box table tfoot td:nth-of-type(3) i").text(total)
    }
    Total()
    // 购物提示
    shopping()
    // 商品数量
    $("body>section .box table tfoot td:nth-of-type(3) span").text($("body>section .box table tbody tr").length)
    // 删除一个商品
    $("body>section .box table tbody td:nth-last-of-type(1)>b").on("click", function () {
        var _this = $(this)
        remove(_this)
    })
    // 删除一个商品函数
    function remove(_this) {
        if (confirm("是否确定删除")) {
            _this.parent().parent().next().remove()
            _this.parent().parent().remove().next()
            for (let i = 0; i < $("body>section .box table tbody em").length; i++) {
                $("body>section>.box>table>tbody [type='checkbox']")[i].setAttribute("index", i)
            }
            $.ajax({
                url: "http://localhost:8888/cart/remove",
                data: {
                    id: localStorage.getItem("id"),
                    goodsId: _this.attr("index"),
                },
                headers: {
                    authorization: localStorage.getItem("token"),
                },
                success: function (res) {
                    if (res.code === 1) {
                        Total()
                        shopping()
                    }
                }
            })
        } else {
            console.log("用户取消了删除");
        }
    }
    // 复选框 tboyd
    $("body>section>.box>table>tbody [type='checkbox']").attr("checked", "true").on("click", function () {
        var a = $("body>section .box table tbody em")[$(this).attr("index")]
        $(a).attr("onoff", this.checked)
        var brr = []
        var num2 = 0
        for (let i = 0; i < $("body>section>.box>table>tbody [type='checkbox']").length; i++) {
            brr.push($("body>section>.box>table>tbody [type='checkbox']")[i])
            if ($("body>section>.box>table>tbody [type='checkbox']")[i].checked == true) {
                num2++
            }
        }
        $("body>section .box table tfoot td:nth-of-type(3) span").text(num2)
        var judge = brr.some(function (v) {
            return v.checked == false
        })
        if (judge) {
            $("body>section>.box>table>tfoot [type='checkbox']")[0].checked = false
        } else {
            $("body>section>.box>table>tfoot [type='checkbox']")[0].checked = true
        }
        $.ajax({
            url: "http://localhost:8888/cart/select",
            type: "post",
            data: {
                id: localStorage.getItem("id"),
                goodsId: +$(this).attr("goodsId"),
            },
            headers: {
                authorization: localStorage.getItem("token")
            },
            success: function (res) {
                console.log(res);
            }
        })
        Total()
    })
    // 复选框 tfoot
    $("body>section>.box>table>tfoot [type='checkbox']").attr("checked", "true").on("click", function () {
        var checked = 1
        for (let i = 0; i < $("body>section>.box>table>tbody [type='checkbox']").length; i++) {
            $("body>section>.box>table>tbody [type='checkbox']")[i].checked = this.checked
        }
        if (this.checked === false) {
            checked = 0
            $("body>section .box table tfoot td:nth-of-type(3) i").text(0)
            $("body>section .box table tfoot td:nth-of-type(3) span").text(0)
            $("body>section .box table tbody em").attr("onoff", false)
        } else {
            checked = 1
            $("body>section .box table tbody em").attr("onoff", "true")
            $("body>section .box table tfoot td:nth-of-type(3) span").text($("body>section>.box>table>tbody [type='checkbox']").length)
            $("body>section .box table tbody em").attr("onoff", true)
            Total()
        }
        $.ajax({
            url: "http://localhost:8888/cart/select/all",
            type: "post",
            data: {
                id: localStorage.getItem("id"),
                type: checked,
            },
            headers: {
                authorization: localStorage.getItem("token")
            },
            success: function (res) {
                console.log(res);
            }
        })
    })
    // 商品数量加减改
    $("body>section>.box>table>tbody [type='text']").on("input", function () {
        $(this).attr("value", `${this.value}`)
        $(this).parent().next().children("em").text((+$(this).parent().prev().children("span").text()) * (+$(this).attr("value")))
        if ($(this).attr("value") == 1) {
            $(this).prev().css({
                background: `rgba(125, 122, 122,.5)`,
            })
        } else {
            $(this).prev().css({
                background: `rgb(243,243,243)`,
            })
        }
        Total()
        if ($(this).attr("value") != 0) {
            $.ajax({
                url: "http://localhost:8888/cart/number",
                type: "post",
                data: {
                    id: localStorage.getItem("id"),
                    goodsId: $(this).attr("goodsid"),
                    number: $(this).attr("value"),
                },
                headers: {
                    authorization: localStorage.getItem("token")
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }
    }).on("focus", function () {
        $(this).attr("value", $(this)[0].value)
        $(this).parent().next().children("em").text((+$(this).parent().prev().children("span").text()) * (+$(this).attr("value")))
        Total()
    })
    $("body>section>.box>table>tbody button:nth-of-type(1)").on("click", function () {
        if ($(this).next().attr("value") > 1) {
            $(this).next().attr("value", `${+$(this).next().attr("value") - 1}`)
        }
        if ($(this).next().attr("value") == 1) {
            $(this).css({
                background: `rgba(125, 122, 122,.5)`,
            })
        } else {
            $(this).css({
                background: `rgb(243,243,243)`,
            })
        }
        $(this).next()[0].value = $(this).next().attr("value")
        $(this).parent().next().children("em").text((+$(this).parent().prev().children("span").text()) * (+$(this).next().attr("value")))
        Total()
        if ($(this).next().attr("value") > 0) {
            $.ajax({
                url: "http://localhost:8888/cart/number",
                type: "post",
                data: {
                    id: localStorage.getItem("id"),
                    goodsId: $(this).attr("goodsid"),
                    number: $(this).next().attr("value"),
                },
                headers: {
                    authorization: localStorage.getItem("token")
                },
                success: function (res) {
                    console.log(res);
                }
            })
        }

    }).next().next().on("click", function () {
        $(this).prev().attr("value", `${+$(this).prev().attr("value") + 1}`)
        $(this).prev()[0].value = $(this).prev().attr("value")
        if ($(this).prev().attr("value") == 1) {
            $(this).prev().prev().css({
                background: `rgba(125, 122, 122,.5)`,
            })
        } else {
            $(this).prev().prev().css({
                background: `rgb(243,243,243)`,
            })
        }
        $(this).parent().next().children("em").text((+$(this).parent().prev().children("span").text()) * (+$(this).prev().attr("value")))
        Total()
        $.ajax({
            url: "http://localhost:8888/cart/number",
            type: "post",
            data: {
                id: localStorage.getItem("id"),
                goodsId: $(this).attr("goodsid"),
                number: $(this).prev().attr("value"),
            },
            headers: {
                authorization: localStorage.getItem("token")
            },
            success: function (res) {
                console.log(res);
            }
        })
    })
    // 清空购物车
    $("body>section>.box>table>tfoot td:nth-of-type(2)").on("click", function () {
        if (confirm("确定删除所有商品吗？")) {
            $("body>section>.box>table>tbody").html(``)
            $("body>section .box table tfoot td:nth-of-type(3) i").text(0)
            $("body>section .box table tfoot td:nth-of-type(3) span").text(0)
            $.ajax({
                url: "http://localhost:8888/cart/clear",
                data: {
                    id: localStorage.getItem("id"),
                },
                headers: {
                    authorization: localStorage.getItem("token")
                },
                success: function (res) {
                    shopping()
                }
            })
        } else {
            console.log("用户取消了清除购物车请求");
        }
    })
    // 支付
    $("body>section .box table tfoot tr td:nth-of-type(4)").on("click", function () {
        $("body>header").before($(`<aside>
        <b>向考拉海购支付</b>
        <span>X</span>
        <p>共<b>${$("body>section .box table tfoot td:nth-of-type(3) i").text()}</b>元</p>
        <button>暂时放弃</button>
        <button>确认支付</button>
        </aside>`))
        $("body>aside button:nth-of-type(1)").on("click", function () {
            $("aside").remove()
        })
        $("body>aside button:nth-of-type(2)").on("click", function () {
            $("aside").remove()
            alert("支付成功！")
            // $("body>section table tbody").empty($("body>section table tbody").children())
            $("body>section>.box>table>tbody [type='checkbox']")
            if($("body>section .box table tfoot tr td:nth-of-type(1) input")[0].checked){
                console.log(123);
                $("body>section .box table tbody").html(``)
                $.ajax({
                    url: "http://localhost:8888/cart/clear",
                    data: {
                        id: localStorage.getItem("id"),
                    },
                    headers: {
                        authorization: localStorage.getItem("token"),
                    },
                    success: function (res) {
                        console.log(res);
                    }
                })
            }else{
                for (let i = 0; i < $("body>section>.box>table>tbody [type='checkbox']").length; i++) {
                    if ($("body>section>.box>table>tbody [type='checkbox']")[i].checked) {
                        var element = $(`body>section>.box>table>tbody [type='checkbox']`)[i]
                        $(element).parent().parent().next().remove()
                        $(element).parent().parent().prev().css({
                            "border-width":"1px 0px 0px 0px"
                        })
                        $(element).parent().parent().remove()
                        $.ajax({
                            url: "http://localhost:8888/cart/remove",
                            data: {
                                id: localStorage.getItem("id"),
                                goodsId:$(element).attr("goodsid"),
                            },
                            headers: {
                                authorization: localStorage.getItem("token"),
                            },
                            success: function (res) {
                                console.log(res);
                            }
                        })
                    }
                }
            }
            
            for (let i = 0; i < $("body>section .box table tbody em").length; i++) {
                console.log(123);
                $("body>section>.box>table>tbody [type='checkbox']")[i].setAttribute("index", i)
            }
            Total()
            shopping()
        })
        $("body>aside span").on("click", function () {
            $("aside").remove()
        })
    })
}
// 购物提示
function shopping() {
    if ($("body>section .box table tbody").children().length === 0) {
        setTimeout(function () {
            if (confirm("购物车空空，快去购物吧！")) {
                location.href = "list.html"
            }
        }, 500)
    }
}

document.querySelector("body")
